<!--
 * @Author: your name
 * @Date: 2021-01-10 12:54:18
 * @LastEditTime: 2021-01-11 21:12:49
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \shopping\src\pages\goods_list\main.vue
-->
<template>
  <view>
    <!-- 搜索 -->
    <Search />
    <!-- tab栏 -->
    <Tabs :tabsList="tabsList" @change="getTabsIndex" />

    <!-- 商品列表 -->
    <view class="goods_list">
      <GoodsItem
        v-for="item in goodsList"
        :item="item"
        :key="item.goods_id"
      ></GoodsItem>
      <view class="tips" v-if="!hasMore">😢我也是有底线的</view>
    </view>
  </view>
</template>

<script>
import { getGoodsList } from "@/api";
import Tabs from "@/components/tabs";
import GoodsItem from "@/components/goodsItem";
export default {
  components: {
    Tabs,
    GoodsItem,
  },
  data() {
    return {
      cid: "",
      query: "",
      pagesize: 10,
      pagenum: 1,
      goodsList: [],
      hasMore: true,
      tabsList: [
        { id: 1, text: "综合" },
        { id: 2, text: "销量" },
        { id: 3, text: "价格" },
      ],
    };
  },
  onLoad({ cid, query }) {
    this.cid = cid;
    this.query = query;

    this.cid ? this.getGoodsList({ cid }) : this.getGoodsList({ query });
  },
  //页面触底事件
  onReachBottom() {
    if (this.hasMore) {
      this.pagenum++;
      this.cid
        ? this.getGoodsList({ cid: this.cid })
        : this.getGoodsList({ query: this.query });
    }
  },
  // 下拉事件
  async onPullDownRefresh() {
    this.pagenum = 1;
    this.goodsList = [];
    this.cid
      ? await this.getGoodsList({ cid: this.cid })
      : await this.getGoodsList({ query: this.query });

    // 请求完成后 主动关闭下拉动画
    uni.stopPullDownRefresh();
  },
  methods: {
    async getGoodsList(data) {
      uni.showLoading({
        title: "拼命加载中！",
      });
      const res = await getGoodsList({
        pagesize: this.pagesize,
        pagenum: this.pagenum,
        ...data,
      });

      const { goods } = res.data.message;
      this.goodsList = [...this.goodsList, ...goods];
      uni.hideLoading();
      if (goods.length < this.pagesize) {
        this.hasMore = false;
      }
    },
    getTabsIndex(index) {
      console.log(index);
    },
  },
};
</script>

<style lang="less" scoped>
.tips {
  display: flex;
  justify-content: center;
}
</style>